<template>
  <el-drawer
    v-model="innerVisible"
    :title="`${title}${pinnedRecord.length ? `（已置顶${pinnedRecord.length}条）` : ''}`"
    size="600px"
    :with-header="true"
    :close-on-press-escape="false"
    @close="close"
    :before-close="beforeClose"
    class="followup-drawer"
  >
    <div class="drawer__wrap">
      <!-- 置顶记录 -->
      <section class="section section--pinned" v-if="pinnedRecord.length">
        <el-scrollbar
          :class="`pinned-scroll ${pinnedRecord.length > 1 ? 'pinned-scroll--fixed' : ''}`"
        >
          <div class="pinned-card" v-for="item in pinnedRecord" :key="item.id">
            <div class="pinned-card__head">
              <el-icon class="pinned-card__pin">
                <Top />
              </el-icon>
              <span class="pinned-card__name">{{ item.createBy }}</span>
              <span class="pinned-card__date">{{ item.createTime }}</span>
              <el-button
                v-if="isSelf(item)"
                class="ml-auto"
                size="small"
                type="danger"
                @click="toggleTop(item, 0)"
                >取消置顶</el-button
              >
            </div>
            <div class="pinned-card__content">{{ item.followRemark }}</div>
          </div>
        </el-scrollbar>
        <LoadMore
          :total="pinnedTotal"
          :count="pinnedRecord.length"
          :loading="pinnedLoadingMore"
          @load="loadPinned"
        />
      </section>

      <!-- 
       hasWritePermission == 'see' 表示不能填写
       -->
      <section class="section section--form" v-if="hasWritePermission !== 'see'">
        <div v-if="!remarkOpen" class="add-remark" @click="remarkOpenPanel" role="button">
          <el-icon class="add-remark__icon">
            <Plus />
          </el-icon>
          填写备注
        </div>

        <transition name="fade-scale" v-else>
          <div class="remark-form">
            <span class="remark-form__label">备注信息</span>
            <!-- rules 更新时 不触发验证 -->
            <el-form
              ref="ruleFormRef"
              :validate-on-rule-change="false"
              :model="ruleForm"
              :rules="rules"
              label-width="auto"
              status-icon
            >
              <el-form-item label="备注内容" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  type="textarea"
                  :rows="2"
                  maxLength="200"
                  show-word-limit
                  placeholder="请输入备注信息"
                />
              </el-form-item>
              <!-- 只有全部权限 -->
              <template v-if="hasWritePermission === 'all'">
                <el-form-item prop="followTimer">
                  <template #label><span class="label">跟踪时间</span></template>
                  <el-radio-group
                    v-model="ruleForm.followTimer"
                    size="small"
                    @change="syncPresetTime"
                  >
                    <el-radio-button value="1" :disabled="isAfterThreePM()"
                      >下午3点</el-radio-button
                    >
                    <el-radio-button value="2">明天8点</el-radio-button>
                    <el-radio-button value="3">明天15点</el-radio-button>
                    <el-radio-button value="4">七天后8点</el-radio-button>
                    <el-radio-button value="5">自定义</el-radio-button>
                  </el-radio-group>
                  <div class="block" v-if="ruleForm.followTimer === '5'">
                    <el-date-picker
                      v-model="ruleForm.customTimer"
                      type="datetime"
                      placeholder="选择下次跟进时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      time-format="HH:mm"
                    />
                  </div>
                </el-form-item>
                <el-form-item prop="dosage">
                  <template #label><span class="label">每日用量</span></template>
                  <el-radio-group v-model="ruleForm.dosage" size="small">
                    <el-radio-button v-for="d in dosageOptions" :key="d.value" :value="d.value">{{
                      d.label
                    }}</el-radio-button>
                  </el-radio-group>
                  <el-space>
                    <div class="block" v-if="ruleForm.dosage === '9'">
                      <el-input-number
                        v-model="ruleForm.customDosage"
                        size="small"
                        :step="0.05"
                        :min="0"
                        :max="10"
                        controls-position="right"
                      />
                    </div>
                    <div class="block">
                      <el-date-picker
                        v-model="ruleForm.usageEndTime"
                        size="small"
                        type="datetime"
                        placeholder="选择用量结束时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </div>
                  </el-space>
                </el-form-item>
              </template>

              <el-form-item>
                <div class="remark-form__actions">
                  <el-button
                    type="primary"
                    size="small"
                    :loading="submitLoading"
                    @click="submitForm(ruleFormRef)"
                    >提交跟踪记录</el-button
                  >
                  <el-button size="small" :disabled="submitLoading" @click="resetForm(ruleFormRef)"
                    >重置</el-button
                  >
                  <el-button size="small" type="info" class="ml-auto" @click="remarkOpen = false"
                    >收起</el-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </div>
        </transition>
      </section>

      <!-- 历史跟进记录 -->
      <section class="section section--history">
        <div class="section-divider" content-position="left">历史跟进（{{ historyTotal }}条）</div>
        <el-scrollbar ref="historyScrollbar" class="history-scroll">
          <template v-if="recordList.length">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in recordList"
                :key="item.id ?? index"
                :timestamp="item.createTime"
                placement="top"
              >
                <div class="history-item">
                  <div class="history-item__head">
                    <div class="history-item__meta">
                      <el-icon class="status ok">
                        <CircleCheckFilled />
                      </el-icon>
                      <span class="history-item__name"
                        >{{ item.nickName }} ({{ item.userName }})</span
                      >
                    </div>

                    <template v-if="isSelf(item)">
                      <div class="history-item__actions" v-if="editingKey !== (item.id ?? index)">
                        <el-space>
                          <el-button link type="primary" @click="startEdit(item, index)"
                            ><el-icon>
                              <EditPen />
                            </el-icon>
                            修改</el-button
                          >
                          <el-button link type="success" @click="toggleTop(item, 1)"
                            ><el-icon>
                              <Top />
                            </el-icon>
                            置顶</el-button
                          >

                          <!-- <el-popconfirm
                            width="200px"
                            title="确认删除此记录吗？操作不可逆！"
                            placement="top-start"
                            @confirm="del(item)"
                          >
                            <template #reference>
                              <el-button link type="danger"
                                ><el-icon>
                                  <Delete />
                                </el-icon>
                                删除</el-button
                              >
                            </template>
                          </el-popconfirm> -->

                          <el-switch
                            v-if="+pageParams.typeCode === 1"
                            v-model="item.isPrivate"
                            :active-value="1"
                            :inactive-value="0"
                            inline-prompt
                            active-text="公开"
                            inactive-text="隐藏"
                            @change="togglePublic(item)"
                          />
                        </el-space>
                      </div>

                      <div class="history-item__actions" v-else>
                        <el-button link type="primary" @click="confirmEdit(item)"
                          ><el-icon>
                            <CircleCheckFilled />
                          </el-icon>
                          确认</el-button
                        >
                        <el-button link type="info" @click="cancelEdit"
                          ><el-icon>
                            <CloseBold />
                          </el-icon>
                          取消</el-button
                        >
                      </div>
                    </template>
                  </div>

                  <div class="history-item__content">
                    <el-space direction="vertical" alignment="normal" style="width: 100%">
                      <el-input
                        v-if="editingKey === (item.id ?? index)"
                        v-model="editText"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入"
                      />
                      <span v-else>{{ item.followRemark }}</span>
                      <span v-if="item.usageAmount">
                        <el-space>
                          <el-tag size="small" effect="plain"
                            >每日用量:{{ item.usageAmount }}</el-tag
                          >
                          <el-tag v-if="item.usageEndTime" type="info" size="small" effect="plain"
                            >用量结束时间:{{ item.usageEndTime }}</el-tag
                          >
                        </el-space>
                      </span>
                    </el-space>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>

            <!-- 使用封装的组件 -->
            <LoadMore
              :total="historyTotal"
              :count="recordList.length"
              :loading="historyLoadingMore"
              @load="loadHistory"
            />
          </template>
          <el-empty v-else description="暂无历史记录" />
        </el-scrollbar>
      </section>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { dayjs, ElMessage } from 'element-plus';
import { Plus, Top, EditPen, CloseBold, CircleCheckFilled, Delete } from '@element-plus/icons-vue';
import {
  addFollowRecord,
  delFollowRecord,
  listFollowRecord,
  updateFollowRecord
} from '../../api/follow/index.js';
import useUserStore from '../../store/modules/user.js';
import { cloneDeep } from 'lodash';

const userApp = useUserStore();
const title = ref('客户跟进详情');
const pinnedRecord = ref<any[]>([]);
const recordList = ref<any[]>([]);
const innerVisible = ref(false);
const submitLoading = ref(false);

// 表单
const remarkOpen = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  remark: '',
  followTimer: '' as '1' | '2' | '3' | '4' | '5' | '',
  customTimer: null as any | null,
  dosage: '' as '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '',
  customDosage: 0 as number | null,
  usageEndTime: null as any | null,
  usageUpdateTime: null as any | null
});
const rules = computed(() => ({
  remark: [
    { required: true, message: '请输入备注', trigger: 'blur' },
    {
      validator: (_val: string, _rule: any, callback: any) => {
        // 备注不能超过200个字符
        if (ruleForm.remark?.trim().length === 0) {
          return callback(new Error('备注不能为空'));
        }
        return true;
      },
      trigger: 'blur'
    }
  ],
  followTimer: [{ required: true, message: '请选择跟踪时间', trigger: 'change' }],
  dosage: [
    {
      validator: (_val: string, _rule: any, callback: any) => {
        // 1. 剂量不能为空
        // 2. 自定义剂量时，剂量不能为空
        if (!ruleForm.dosage || (ruleForm.dosage === '9' && !ruleForm.customDosage)) {
          return callback(new Error('请输入剂量'));
        }

        // 计量结束时间必须存在（非必填）
        // if (!ruleForm.usageEndTime) {
        //   return callback(new Error('请选择计量结束时间'));
        // }
        // 计量结束时间不能早于当前时间
        if (ruleForm.usageEndTime && dayjs(ruleForm.usageEndTime).isBefore(dayjs())) {
          return callback(new Error('计量结束时间不能早于当前时间'));
        }
        return true;
      },
      trigger: 'change'
    }
  ]
}));

const dosageOptions = [
  { value: '1', label: '1/3' },
  { value: '2', label: '0.5' },
  { value: '3', label: '2/3' },
  { value: '4', label: '1' },
  { value: '5', label: '1.5' },
  { value: '6', label: '2' },
  { value: '7', label: '2.5' },
  { value: '8', label: '3' },
  { value: '9', label: '自定义' }
];

// 判断当前时间是否超过下午三点
const isAfterThreePM = () => {
  const now = new Date();
  const hour = now.getHours();
  return hour >= 15;
};

// 编辑历史(编辑的key)
const editingKey = ref<string | number | null>(null);
const editText = ref('');

const emit = defineEmits(['ok']);

// 分页状态
const pageParams = reactive({
  customerId: 0,
  typeCode: 0
});

const pinnedPage = reactive({ pageNum: 1, pageSize: 100 });
const historyPage = reactive({ pageNum: 1, pageSize: 150 });

// 获取置顶记录
const pinnedTotal = ref(0);
const pinnedLoadingMore = ref(false);

async function loadPinned() {
  pinnedLoadingMore.value = true;
  const res = await listFollowRecord({
    ...pageParams,
    topStatus: 1,
    pageNum: pinnedPage.pageNum,
    pageSize: pinnedPage.pageSize
  });
  pinnedLoadingMore.value = false;
  if (res.code === 200) {
    pinnedRecord.value = res.rows;
    pinnedTotal.value = parseInt(res.total);
    pinnedPage.pageSize += 100;
  }
}

// 获取历史记录
const historyTotal = ref(0);
const historyLoadingMore = ref(false);

async function loadHistory() {
  historyLoadingMore.value = true;
  const res = await listFollowRecord({
    ...pageParams,
    topStatus: 0,
    pageNum: historyPage.pageNum,
    pageSize: historyPage.pageSize
  });
  historyLoadingMore.value = false;
  if (res.code === 200) {
    recordList.value = res.rows;
    historyTotal.value = parseInt(res.total);
    historyPage.pageSize += 100;
  }
}

/**
 * 根据预设值生成目标时间
 * 1 → 今天下午15点
 * 2 → 明天上午8点
 * 3 → 明天下午15点
 * 4 → 7天后当前时间
 * 5 → 不处理（直接返回）
 */
function syncPresetTime(val: string) {
  if (val === '5') return;
  const now = dayjs();
  let target: dayjs.Dayjs;

  switch (val) {
    case '1': // 今天下午三点
      target = now.hour(15).minute(0).second(0);
      // 如果当前时间已经过了三点，就自动顺延到明天下午三点
      if (now.isAfter(target)) {
        ElMessage.warning('当前时间已过下午三点，自动顺延到明天下午三点');
        ruleForm.followTimer = '3';
        target = target.add(1, 'day');
      }
      break;
    case '2': // 明天早上八点
      target = now.add(1, 'day').hour(8).minute(0).second(0);
      break;
    case '3': // 明天下午三点
      target = now.add(1, 'day').hour(15).minute(0).second(0);
      break;
    case '4': // 七天后早晨八点
      target = now.add(7, 'day').hour(8).minute(0).second(0);
      break;
    default:
      return;
  }
  ruleForm.customTimer = target.format('YYYY-MM-DD HH:mm:ss');
}

// 打开备注面板 并根据最近记录的用量自动设置剂量选项
const latestRecord = ref<any>({});
const remarkOpenPanel = () => {
  remarkOpen.value = true;
  // 合并pinnedRecord和recordList数组
  const allRecords = [...pinnedRecord.value, ...recordList.value];
  // 根据createTime日期排序（降序，最新的在前）
  const sortedRecords = allRecords.sort((a, b) => {
    // 假设createTime是字符串格式的日期时间
    return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
  });
  // 获取最新的记录
  const latestRecord = sortedRecords[0];
  latestRecord.value = latestRecord;
  // 如果有最新记录，可以根据需要使用它的信息
  if (latestRecord && latestRecord.usageAmount) {
    // 可以根据最近记录的用量自动设置剂量选项
    // 这里需要根据实际的数据结构和业务需求进行适当调整
    const getValue: any = dosageOptions.find((v) => v.label == latestRecord.usageAmount);
    if (getValue) {
      ruleForm.dosage = getValue.value;
      ruleForm.usageEndTime = latestRecord.usageEndTime;
    } else {
      // 最近记录的用量不在预选项中，设置为自定义
      ruleForm.dosage = '9';
      ruleForm.customDosage = latestRecord.usageAmount;
      ruleForm.usageEndTime = latestRecord.usageEndTime;
    }
  }
};

// 提交表单
function normalizeDosage(): number | string {
  if (ruleForm.dosage === '9') return ruleForm.customDosage ?? '';
  const map: any = {
    '1': (0.3).toFixed(2),
    '2': (0.5).toFixed(2),
    '3': (0.7).toFixed(2),
    '4': (1).toFixed(2),
    '5': (1.5).toFixed(2),
    '6': (2).toFixed(2),
    '7': (2.5).toFixed(2),
    '8': (3).toFixed(2)
  };
  return map[ruleForm.dosage] ?? '';
}

// 提交表单
async function submitForm(formEl: any) {
  if (!formEl) return;
  await formEl.validate((valid: boolean) => {
    if (!valid) return;
    submitLoading.value = true;
    const usageAmount = normalizeDosage();
    // 取出最新得一条历史记录得用量 是否与当前用量一致
    // 1. 如果不一致，更新时间用量完成时间
    if (latestRecord.value.usageAmount !== usageAmount) {
      // 用量更新时间 当前时间 格式：YYYY-MM-DD HH:mm:ss
      ruleForm.usageUpdateTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }

    addFollowRecord({
      // 客户id
      customerId: pageParams.customerId,
      // 跟进类型：0 1
      typeCode: pageParams.typeCode,
      // 跟进备注
      followRemark: ruleForm.remark,
      // 跟进时间
      contactNextTime: ruleForm.customTimer ? ruleForm.customTimer : '',
      // 跟进剂量
      usageAmount,
      // 计量结束时间
      usageEndTime: ruleForm.usageEndTime,
      // 用量更新时间
      usageUpdateTime: ruleForm.usageUpdateTime
    })
      .then((res: any) => {
        submitLoading.value = false;
        if (res.code === 200) {
          ElMessage.success('提交成功');
          resetForm(formEl);
          remarkOpen.value = false;
          emit('ok');
          // 获取历史记录
          loadHistory();
        }
      })
      .catch(() => {
        submitLoading.value = false;
      });
  });
}

// 重置表单
function resetForm(formEl: any) {
  ruleForm.customTimer = null;
  ruleForm.customDosage = null;
  ruleForm.usageEndTime = null;
  ruleForm.dosage = '';
  formEl?.resetFields?.();
}

// 置顶
// topStatus 置顶状态 0 未置顶 1 已置
function toggleTop(item: any, topStatus: any) {
  updateFollowRecord({
    id: item.id,
    topStatus
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('已保存修改');
      loadHistory();
      loadPinned();
    }
  });
}

// 公开
// isPrivate 隐私状态 0隐私  1公开
function togglePublic(item: any) {
  updateFollowRecord({
    id: item.id,
    isPrivate: item.isPrivate
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('已保存修改');
      loadHistory();
    }
  });
}

// 修改备注
function confirmEdit(item: any) {
  updateFollowRecord({
    id: item.id,
    followRemark: editText.value
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('已保存修改');
      item.followRemark = editText.value;
      cancelEdit();
      emit('ok');
    }
  });
}

// 判断是否是本人发布的
function isSelf(item: any) {
  return item.userId === userApp.id;
}

// 判断当前角色是否有填写权限
const hasWritePermission = computed(() => {
  // 销售 = saleUser
  // 客服 = customerService
  // 超管 总经理 = boss admin
  // 如果权限是客服，但是typeCode是销售，则只能查看，不能填报
  // 如果权限是销售，但是typeCode是客服，则只能查看，不能填报
  // 如果权限是客服，但是typeCode是客服，可以填报，但是不用填写用量和下次跟踪
  // 如果权限是销售，但是typeCode是销售，可以完整使用
  // 如果权限是原总，只能查看 不能填报

  // 定义权限值：
  // see 仅查看
  // all 可填写（所有字段）
  // no 不支持输入
  // input 可填写（仅输入框）
  // typeCode === 1 是 "客服" 其他表示 "销售";
  const userCode = cloneDeep(userApp.roles);

  // 超管角色
  if (userCode.includes('admin')) {
    return 'all';
  }

  // 原总角色
  if (userCode.includes('boss')) {
    return 'see';
  }

  // 客服角色
  if (userCode.includes('customerService')) {
    // 判断是否是客服
    if (pageParams.typeCode === 1) {
      return 'input';
    }
    return 'see';
  }
  // 销售角色
  if (userCode.includes('saleUser')) {
    // 判断是否是销售
    if (pageParams.typeCode === 2) {
      return 'all';
    }
    return 'see';
  }
  // 其他角色
  return 'see';
});

// 历史编辑
function startEdit(item: any, index: number) {
  editingKey.value = item.id ?? index;
  editText.value = item.followRemark;
}

function cancelEdit() {
  editingKey.value = null;
  editText.value = '';
}

// 删除
function del(row: any) {
  delFollowRecord(row.id).then((res: any) => {
    if (res.code === 200) loadHistory();
    emit('ok');
  });
}

// 对外方法
function show(row: any, typeCode: number) {
  // 重置表单
  const formEl: any = ruleFormRef.value;
  resetForm(formEl);
  title.value = typeCode === 1 ? '客服跟进记录' : '销售跟进记录';
  pageParams.customerId = row.customerId;
  pageParams.typeCode = typeCode;

  // 重置分页状态
  pinnedRecord.value = [];
  pinnedPage.pageNum = 1;
  recordList.value = [];
  historyPage.pageNum = 1;

  loadPinned();
  loadHistory();
  innerVisible.value = true;
  submitLoading.value = false;
}

// 关闭前检测如果表单通过验证,保存+关闭 否则不允许关闭
async function beforeClose(done: () => void) {
  // 如果备注区域未打开，直接关闭
  // 如果是客服 也可以直接关闭
  if (!remarkOpen.value || pageParams.typeCode !== 1) {
    done();
    return;
  }

  if (pageParams.typeCode === 1 && !ruleForm.remark.trim()) {
    done();
    return;
  }

  const formEl: any = ruleFormRef.value;
  if (!formEl) {
    done();
    return;
  }

  try {
    // 使用 promise 风格的 validate，校验不通过会抛出错误
    await formEl.validate();
    // 校验通过后提交数据
    submitLoading.value = true;
    const res: any = await addFollowRecord({
      customerId: pageParams.customerId,
      typeCode: pageParams.typeCode,
      followRemark: ruleForm.remark,
      contactNextTime: ruleForm.customTimer ? ruleForm.customTimer : '',
      usageAmount: normalizeDosage()
    });
    submitLoading.value = false;

    if (res && res.code === 200) {
      ElMessage.success('提交成功');
      resetForm(formEl);
      remarkOpen.value = false;
      emit('ok');
      // 刷新历史记录
      loadHistory();
      // 允许关闭抽屉
      done();
    } else {
      ElMessage.error((res && res.message) || '提交失败');
    }
  } catch (err) {
    // 验证未通过或其他异常，阻止关闭并提示
    ElMessage.info('请填写完整跟踪记录或收起后关闭!');
    submitLoading.value = false;
  }
}

function close() {
  innerVisible.value = false;
  submitLoading.value = false;
}

defineExpose({ show, close });
</script>

<style lang="scss">
.followup-drawer {
  --card-bg: #fffaf3;
  --muted: #8b8b8b;
  --text: #333;
  --border: #e6e6e6;

  .el-drawer__body {
    display: flex;
  }
}

.drawer__wrap {
  flex: 1;
  display: grid;
  grid-template-rows: auto auto 1fr;
  gap: 12px;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.section {
  &-divider {
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 16px;
    color: #606266;
    line-height: 32px;
    padding: 0 0 10px 0;
  }

  &--pinned--fixed {
    height: 300px;
  }

  &--pinned {
    background: var(--card-bg);

    .pinned-scroll--fixed {
      height: 140px;
    }

    .pinned-card {
      height: 70px;
      border-radius: 5px;
      padding: 10px;

      &__head {
        display: flex;
        align-items: center;
        font-size: 16px;
        color: var(--text);
      }

      &__pin {
        transform: rotate(0deg);
      }

      &__name {
        font-weight: 600;
      }

      &__date {
        margin-left: 24px;
        color: #666;
        font-size: 13px;
      }

      &__content {
        margin-bottom: 5px;
        border-radius: 5px;
        padding: 5px;
        color: #666;
        font-size: 14px;
      }
    }
  }

  .add-remark {
    width: 100%;
    padding: 8px 10px;
    border: 1px dashed var(--border);
    border-radius: 5px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    color: #999;
    cursor: pointer;
    user-select: none;

    &:hover {
      border-color: #d0d0d0;
    }

    &__icon {
      font-size: 16px;
    }
  }

  &--form {
    .remark-form {
      border: 1px solid var(--border);
      border-radius: 5px;
      padding: 35px 16px 4px 16px;
      position: relative;

      .remark-form__label {
        position: absolute;
        display: inline-block;
        padding: 5px 10px;
        background: #ebebeb;
        margin-bottom: 10px;
        border-radius: 0 5px 5px 0;
        left: 0;
        top: 0;
        font-size: 14px;
        color: #606266;
      }

      .label {
        color: var(--muted);
      }

      .block {
        // padding: 10px 0 0;
      }

      &__actions {
        display: flex;
        align-items: center;
        width: 100%;

        .ml-auto {
          margin-left: auto;
        }
      }
    }
  }

  &--history {
    display: flex;
    flex-direction: column;
    flex: 1;
    position: relative;
    overflow: hidden;

    .history-scroll {
      height: 100%;
    }

    .history-item {
      &__head {
        display: flex;
        align-items: center;
        gap: 12px;
      }

      &__meta {
        display: flex;
        align-items: center;
        gap: 8px;
        color: var(--text);
      }

      &__name {
        font-weight: 600;
      }

      &__actions {
        margin-left: auto;
        display: inline-flex;
        gap: 6px;
      }

      &__content {
        color: #777;
        line-height: 1.7;
        padding-top: 8px;
        white-space: pre-wrap;
      }

      .status {
        font-size: 16px;

        &.ok {
          color: #67c23a;
        }

        &.warn {
          color: #f56c6c;
        }
      }
    }
  }
}

.ml-auto {
  margin-left: auto;
}

/* 轻盈过渡 */
.fade-scale-enter-active,
.fade-scale-leave-active {
  transition: all 0.18s ease;
}

.fade-scale-enter-from,
.fade-scale-leave-to {
  opacity: 0;
  transform: scale(0.98);
}
</style>

<style lang="scss">
.el-drawer__header {
  margin-bottom: 0;
}
</style>
